package cn.javadog.ss.spring.ioc.beanfactory;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;

/**
 * @author 余勇
 * @date 2019年11月24日 14:46:00
 * spring-test 使用的是 applicationContext
 */
public class BeanfactoryBootstrap {

	private static final String BEANFACTORY_XML_CLASSPATH = "beanFactoryTest.xml";

	/**
	 * 获取beanFactory
	 * NOTE spring5不推荐使用xmlBeanFactory, 而是直接使用 DefaultListableBeanFactory + XmlBeanDefinitionReader
	 */
	public static DefaultListableBeanFactory getBeanFactory() {
		DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
		reader.loadBeanDefinitions(new ClassPathResource(BEANFACTORY_XML_CLASSPATH));
		return beanFactory;
	}


	public static void main(String[] args) {
		// 获取beanFactory
		DefaultListableBeanFactory beanFactory = getBeanFactory();
		// beanFactory.addBeanPostProcessor(new SimpleBean());

		// 测试简单bean的获取，没有任何属性和构造（只有默认构造）
		getSimpleBean(beanFactory);
		System.out.println("<=============测试简单bean的获取 测试结束==============>");

		// 测试两个不同的scope
		testScope(beanFactory);
		System.out.println("<=============测试两个不同的scope 测试结束==============>");
	}

	/**
	 * 简单bean的获取
	 */
	public static void getSimpleBean(BeanFactory beanFactory) {
		SimpleBean simpleBean = beanFactory.getBean(SimpleBean.class);
		simpleBean.sayHi();
	}

	/**
	 * 测试Scope
	 * beanFactory就两个域 singleton prototype
	 */
	public static void testScope(BeanFactory beanFactory) {
		TestScopeBean singletonScopeBean1 = beanFactory.getBean("singletonScopeBean",TestScopeBean.class);
		TestScopeBean singletonScopeBean2 = beanFactory.getBean("singletonScopeBean",TestScopeBean.class);

		TestScopeBean prototypeScopeBean1 = beanFactory.getBean("prototypeScopeBean",TestScopeBean.class);
		TestScopeBean prototypeScopeBean2 = beanFactory.getBean("prototypeScopeBean",TestScopeBean.class);
	}

}
